<template>
  <el-dialog
      :title="isEdit ? '编辑文章' : '新增文章'"
      v-model="visible"
      width="800px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="articleFormRef"
        :model="articleForm"
        :rules="formRules"
        label-width="100px"
        size="default"
    >
      <!-- 文章标题 -->
      <el-form-item label="文章标题" prop="title">
        <el-input
            v-model="articleForm.title"
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 文章分类 -->
      <el-form-item label="文章分类" prop="categoryId">
        <el-select
            v-model="articleForm.categoryId"
            placeholder="请选择文章分类"
            clearable
        >
          <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 文章摘要 -->
      <el-form-item label="文章摘要" prop="summary">
        <el-input
            v-model="articleForm.summary"
            placeholder="请输入文章摘要（可选）"
            type="textarea"
            rows="3"
            maxlength="500"
            show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 文章内容 -->
      <el-form-item label="文章内容" prop="content">
        <div class="editor-container">
          <!-- 简化版富文本编辑器 -->
          <el-input
              v-model="articleForm.content"
              placeholder="请输入文章内容"
              type="textarea"
              rows="15"
          ></el-input>

          <!-- 实际项目中可替换为专业富文本编辑器 -->
          <!-- <Tinymce v-model="articleForm.content" /> -->
        </div>
      </el-form-item>

      <!-- 封面图片 -->
      <el-form-item label="封面图片">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/image"
            :show-file-list="false"
            :on-success="handleImageUploadSuccess"
            :before-upload="beforeImageUpload"
        >
          <img
              v-if="articleForm.coverImage"
              :src="articleForm.coverImage"
              class="avatar"
              alt="文章封面"
          >
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">支持JPG、PNG格式，建议尺寸1200×600</div>
      </el-form-item>

      <!-- 发布状态 -->
      <el-form-item label="发布状态" prop="status">
        <el-radio-group v-model="articleForm.status">
          <el-radio label="published">立即发布</el-radio>
          <el-radio label="draft">保存为草稿</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
      >
        {{ isEdit ? '更新文章' : '发布文章' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, watch, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getCategories, getArticleDetail, addArticle, updateArticle } from '@/api/news';

// 组件props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  articleId: {
    type: [String, Number, null],
    default: null
  }
});

// 组件emit
const emit = defineEmits(['update:visible', 'refreshList']);

// 状态管理
const state = reactive({
  // 表单数据
  articleForm: {
    title: '',
    categoryId: '',
    summary: '',
    content: '',
    coverImage: '',
    status: 'published' // 默认发布状态
  },
  // 分类列表
  categories: [],
  // 表单规则
  formRules: {
    title: [
      { required: true, message: '请输入文章标题', trigger: 'blur' },
      { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    categoryId: [
      { required: true, message: '请选择文章分类', trigger: 'change' }
    ],
    content: [
      { required: true, message: '请输入文章内容', trigger: 'blur' },
      { min: 10, message: '文章内容不能少于10个字符', trigger: 'blur' }
    ]
  },
  // 表单引用
  articleFormRef: ref(null),
  // 提交加载状态
  submitLoading: false,
  // 是否为编辑模式
  isEdit: false
});

const {
  articleForm,
  categories,
  formRules,
  articleFormRef,
  submitLoading,
  isEdit
} = toRefs(state);

// 监听articleId变化，判断是否为编辑模式
watch(
    () => props.articleId,
    (newVal) => {
      state.isEdit = !!newVal;
      if (newVal) {
        // 编辑模式，加载文章详情
        fetchArticleDetail(newVal);
      } else {
        // 新增模式，重置表单
        resetForm();
      }
    },
    { immediate: true }
);

// 监听visible变化
watch(
    () => props.visible,
    (newVal) => {
      if (newVal && !props.articleId) {
        // 显示且不是编辑模式，重置表单
        resetForm();
      }
    }
);

// 页面加载时获取分类列表
onMounted(() => {
  fetchCategories();
});

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getCategories();
    state.categories = response.data;
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + (error.message || '未知错误'));
  }
};

// 获取文章详情
const fetchArticleDetail = async (id) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    target: document.querySelector('.el-dialog__body')
  });

  try {
    const response = await getArticleDetail(id);
    const article = response.data;

    // 填充表单数据
    state.articleForm = {
      title: article.title,
      categoryId: article.categoryId,
      summary: article.summary || '',
      content: article.content,
      coverImage: article.coverImage || '',
      status: article.status || 'published'
    };
  } catch (error) {
    ElMessage.error('获取文章详情失败: ' + (error.message || '未知错误'));
  } finally {
    loading.close();
  }
};

// 重置表单
const resetForm = () => {
  state.articleForm = {
    title: '',
    categoryId: '',
    summary: '',
    content: '',
    coverImage: '',
    status: 'published'
  };

  if (state.articleFormRef.value) {
    state.articleFormRef.value.clearValidate();
  }
};

// 处理图片上传成功
const handleImageUploadSuccess = (response) => {
  if (response.code === 200) {
    state.articleForm.coverImage = response.data.url;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败: ' + (response.msg || '未知错误'));
  }
};

// 上传前校验
const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }

  return true;
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  const valid = await state.articleFormRef.value.validate();
  if (!valid) return;

  state.submitLoading = true;

  try {
    if (state.isEdit) {
      // 编辑文章
      await updateArticle(props.articleId, state.articleForm);
      ElMessage.success('文章更新成功');
    } else {
      // 新增文章
      await addArticle(state.articleForm);
      ElMessage.success('文章发布成功');
    }

    // 关闭弹窗并通知父组件刷新列表
    emit('update:visible', false);
    emit('refreshList');
  } catch (error) {
    ElMessage.error(`${state.isEdit ? '更新' : '发布'}失败: ` + (error.message || '未知错误'));
  } finally {
    state.submitLoading = false;
  }
};

// 处理弹窗关闭
const handleClose = () => {
  // 清除表单验证
  if (state.articleFormRef.value) {
    state.articleFormRef.value.clearValidate();
  }
  emit('update:visible', false);
};
</script>

<style scoped>
.editor-container {
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  transition: border-color 0.2s;
}

.editor-container:focus-within {
  border-color: #409eff;
  outline: none;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px dashed #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
}

.el-textarea__inner {
  min-height: 300px;
}
</style>
